package com.peanuts.tender.test;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <b>加密工具类</b>
 * <br>支持md5加密、sha-1加密、sha-256加密
 * <br><br><b>对hex型的字符串进行加密处理：md5_hex:md5加密、sha1_hex:sha-1加密、sha256_hex:sha-256加密 </b>
 * <br>&nbsp;&nbsp;&nbsp;&nbsp;hex型字符串例子：对byte数组：{0x01,0x02,0xB2}进行hex型字符串转化："0102B2"
 * 对"0102B2进行加密：F35F0B616913917B6E335799DEB063ECBBCC516B
 * <br><b><p>对普通（包括中文）字符串进行加密处理：md5:md5加密、sha1:sha-1加密、sha256:sha-256加密</b>
 * <br>&nbsp;&nbsp;&nbsp;&nbsp;普通（包括中文）字符串例子：对"Hello,world!进行加密：FBB7FF0741FAAD264C45DAA6A5D623C0581DEF9B
 * <br>
 * @author 贺楚源
 *
 */
public class EncryptUtil {
	
	/**
     * md5加密  
     * @param inputText 需要加密的字符串
     * @return
     */
    public String md5(String inputText) {  
        return encrypt(inputText, "md5");  
    }  
    /**
     * md5加密  
     * @param inputhexString (16进制字符串) 需要加密的字符串
     * @return
     */
    public String md5_hex(String inputHexString) {  
        return hex_encrypt(inputHexString, "md5");  
    } 
  
    /**
     * sha-1加密
     * @param inputText 需要加密的字符串
     * @return
     */
    public String sha1(String inputText) {  
        return encrypt(inputText, "sha-1");  
    } 
    /**
     * sha-1加密
     * @param inputhexString (16进制字符串)需要加密的字符串
     * @return
     */
    public String sha1_hex(String inputHexString) {  
        return hex_encrypt(inputHexString, "sha-1");  
    } 
    
    /**
     * sha-256加密
     * @param inputText 需要加密的字符串
     * @return
     */
    public String sha256(String inputText) {  
        return encrypt(inputText, "sha-256");  
    }
    /**
     * sha-256加密
     * @param inputhexString (16进制字符串)需要加密的字符串
     * @return
     */
    public String sha256_hex(String inputHexString) {  
        return hex_encrypt(inputHexString, "sha-256");  
    } 
  
    /** 
     * md5或者sha-1加密 
     *  
     * @param inputhexString (16进制字符串)
     *            要加密的内容 
     * @param algorithmName 
     *            加密算法名称：md5或者sha-1，不区分大小写 
     * @return 
     */  
    private String encrypt(String inputText, String algorithmName) {  
        if (inputText == null || "".equals(inputText.trim())) {  
            throw new IllegalArgumentException("请输入要加密的内容");  
        }  
        if (algorithmName == null || "".equals(algorithmName.trim())) {  
            algorithmName = "md5";  
        }  
        String encryptText = null;  
        try {  
            MessageDigest m = MessageDigest.getInstance(algorithmName);  
            m.update(inputText.getBytes("UTF8"));  
            byte s[] = m.digest();  
            // m.digest(inputText.getBytes("UTF8"));  
            return hex(s);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return encryptText;  
    }  
    

    /** 
     * md5或者sha-1加密 
     *  
     * @param inputhexString (16进制字符串)
     *            要加密的内容 
     * @param algorithmName 
     *            加密算法名称：md5或者sha-1，不区分大小写 
     * @return 
     */  
    private String hex_encrypt(String inputHexString, String algorithmName) {  
        if (inputHexString == null || "".equals(inputHexString.trim())) {  
            throw new IllegalArgumentException("请输入要加密的内容");  
        }  
        if (algorithmName == null || "".equals(algorithmName.trim())) {  
            algorithmName = "md5";  
        }  
        String encryptText = null;  
        try {  
            MessageDigest m = MessageDigest.getInstance(algorithmName);  
            m.update(hexStringToBytes(inputHexString));  
            byte s[] = m.digest();  
            // m.digest(inputText.getBytes("UTF8"));  
            return hex(s);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return encryptText;  
    }  
  
    /**
     * 返回十六进制字符串  
     * @param arr
     * @return
     */
    private String hex(byte[] arr) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < arr.length; ++i) {  
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,  
                    3));  
        }  
        return sb.toString();  
    }
    
    /**
	 * 将16进制字符串转换成byte[] 数组
	 * **/
	public static byte[] hexStringToBytes(String hexString) {   
		if (hexString == null || hexString.equals("")) {   
			return null;   
		}   
		hexString = hexString.toUpperCase();   
		int length = hexString.length() / 2;   
		char[] hexChars = hexString.toCharArray();   
		byte[] d = new byte[length];   
		for (int i = 0; i < length; i++) {   
			int pos = i * 2;   
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));   
		}   
		return d;   
	}
	private static byte charToByte(char c) {   
		return (byte) "0123456789ABCDEF".indexOf(c);   
	}
}
